﻿package z.myServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
//https://blog.csdn.net/qq_34740590/article/details/79700162
//字符通信

public class JClient {

    public static void main(String[] args) throws UnknownHostException, IOException {
        //Socket socket = new Socket("39.108.12.42", 9050);
        Socket socket = new Socket("127.0.0.1", 9050);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        //DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        //DataInputStream in = new DataInputStream(socket.getInputStream());
        Scanner scanner = new Scanner(System.in);
        String p = null;
        byte[] buff = new byte[1024];
        while (true) {
            try {
                int len;
                System.out.println("please input...");

                p = scanner.nextLine();

                os.write(serialize(p));

                //out.writeUTF(p);

               //mp.setMessage(p);
                //
                if (is.read(buff) == -1) System.out.println("read error");
                len = byteToInt(buff, 0);
                System.out.println("len: " + len);
                System.out.println("server: " + unserialize(buff));
            } catch (Exception e) {
                socket.close();
                e.printStackTrace();
            }
        }
    }

        public static byte[] serialize(String message) {
                byte[] temp = message.getBytes();
                int totalLength = temp.length + 4;
                byte[] buffer = new byte[totalLength];
                int offset = 0;
                System.out.println(totalLength);
                byte[] totalLengthBuffer = intToByte(totalLength);
                System.arraycopy(totalLengthBuffer, 0, buffer, offset, 4);
                offset += 4;

                System.arraycopy(temp, 0, buffer, offset, temp.length);
                return buffer;

        }

        public static String unserialize(byte[] data) {
                int totalLength = byteToInt(data, 0);
                return new String(data, 4, totalLength - 4);
        }

        public static byte[] intToByte(int num) {
                byte[] buffer = new byte[4];
                //https://blog.csdn.net/u013556056/article/details/81019509
                for (int i = 0; i < 4; i++) {
                        buffer[i] = (byte) (num >> 8 * i);
                }
                return buffer;
        }

        public static int byteToInt(byte[] buffer, int offset) {
                int num = 0;
                for (int i = 0; i < 4; i++) {
                        num += (int) (buffer[i + offset] << 8 * i);
                }
                return num;
        }
}